package commons.util;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 1. 构造方法，参数使用字符串
 * 2. 判等比较不要用 equals，用 compareTo
 * 3. 保留有效数字不要用 round，用 setScale
 */
public class BigNumber {

  static void noTrailingZero(String number) {
    BigDecimal decimal = new BigDecimal(number);
    decimal = decimal.stripTrailingZeros();
    System.out.println(number + " 去掉末尾 0 以后：" + decimal);
  }

  static void keepTwoSignificantNumbers(String number) {
    BigDecimal decimal = new BigDecimal(number);
    decimal = decimal.setScale(2, RoundingMode.HALF_UP);
    System.out.println(number + " 保留两位有效数字以后：" + decimal);
  }

  // 这有卵用？
  static void whatHappensIfScaleIsNegative(String number) {
    BigDecimal decimal = new BigDecimal(number);
    decimal = decimal.setScale(-2, RoundingMode.HALF_UP);
    BigDecimal compared = new BigDecimal(new BigDecimal(number).intValue() / 100 * 100);
    System.out.println("手动对 100 取整：" + compared);
    System.out.println("setScale -2 之后的值：" + decimal);
    System.out.println("equals 判等：" + compared.equals(decimal));
    System.out.println("compareTo 判等：" + (compared.compareTo(decimal) == 0));
  }

  public static void main(String[] args) {
    noTrailingZero("1.00");
    keepTwoSignificantNumbers("2.333");
    whatHappensIfScaleIsNegative("100.11");
  }
}
